package com.hl.security.filter;

import com.hl.security.UserDetail;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**权限过滤拦截器
 * Created by aaron on 2017/1/13.
 */
public class WebPermInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if( SecurityContextHolder.getContext().getAuthentication()!=null){
            UserDetail userDetail = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            HttpServletRequest req=(HttpServletRequest)request;
            System.out.println("userD"+userDetail.getUsername());
            req.getSession().setAttribute("userD",userDetail.getUsername());
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            Object target = hm.getBean();
            Class<?> clazz = hm.getBeanType();
            Method m = hm.getMethod();
            if (clazz != null && m != null) {
                boolean isMethondAnnotation = m.isAnnotationPresent(RequestMapping.class);
                if (isMethondAnnotation) {
                    RequestMapping rc = m.getAnnotation(RequestMapping.class);
                    String[] urlVals = rc.value();
                    if (urlVals != null && urlVals.length > 0 && !hasPrem(urlVals[0])) {
                        if (isAjaxRequest(request)) {
                            //未授权访问,返回false
                            response.setStatus(403);
                            response.getWriter().println("do not have permission to access the resource, please contact the administrator");
                            return false;
                        } else {
                            response.sendRedirect("http://localhost/403.html");
                        }


                    }
                }
            }

        }
        return true;
    }

    private boolean hasPrem(String permKey) {
        System.out.println("urlVals lenght" + permKey);
        try {
            UserDetail userDetail = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<String> resources = userDetail.getResourceUrls();
            for (String sysResource : resources) {
                if (permKey.equals(sysResource)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }

    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
